<template>
  <div :class="[$style.container]">
    <div :class="[$style.header]">
      <el-link :underline="false" @click="onBack"><i class="el-icon-back ft-lg"></i></el-link>
      <span class="ml-3">忘记密码</span>
    </div>
    <el-form :model="form" :rules="rules" ref="fm">
      <el-form-item prop="identifier" required>
        <el-input v-model.trim="form.identifier" placeholder="请输入手机号、邮箱"></el-input>
      </el-form-item>
    </el-form>

    <div :class="[$style.action]" class="mt-5">
      <el-button type="primary" :loading="submitting" @click="onNext" style="width: 100%;">下一步</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Ref, Vue } from 'vue-property-decorator'
import { emailOrPhoneValidator } from '@/config/validator'
import { isEmail } from '@/utils/validation'
import { isBoundWithPassword } from '@/api/account'

@Component
export default class Step1 extends Vue {
  @Ref() fm!: any

  @Prop() stepData!: any

  submitting = false

  form = {
    identifier: this.stepData.identifier || ''
  }

  get rules () {
    return {
      identifier: [
        { required: true, message: '请输入正确的手机号或邮箱' },
        { validator: emailOrPhoneValidator }
      ]
    }
  }

  onNext () {
    this.fm.validate().then((valid: boolean) => {
      if (!valid) return
      const type = isEmail(this.form.identifier) ? 'email' : 'phone'
      this.submitting = true
      isBoundWithPassword(this.form.identifier, type).then(data => {
        if (data) {
          this.stepData.identifier = this.form.identifier
          this.stepData.type = type
          this.stepData.step = 2
        } else {
          this.$message.error('该账号不存在')
        }
      }).finally(() => {
        this.submitting = false
      })
    })
  }

  onBack () {
    this.$router.go(-1)
  }
}
</script>

<style lang="scss" module>
@import "~@/styles/vars.scss";

.container {

}

.header {
  margin-bottom: 12px;
  font-size: 16px;
}

.action {
  display: flex;
  justify-content: space-between;
}
</style>
